package com.shirley.ws.server.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class WebsocketServerHandler extends TextWebSocketHandler {

    private static AtomicInteger msgCount = new AtomicInteger(0);

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("Get message from client: {}", message.getPayload());
        session.sendMessage(new TextMessage("This is the " + msgCount.incrementAndGet() + " message."));
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("Connection established.");
    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("Connection established.");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.info("Connection closed.");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
